package org.madmatrix.glib.util;

import com.google.gson.JsonObject;

/**
 * 对com.google.gson进行扩展，使其具有org.json的风格
 * 
 * @author madmatrix
 */
public class JsonUtil {
	
	public static JsonObject getJsonObject(JsonObject jsonObj, String name) {
		if (null == jsonObj || null == jsonObj.get(name)) {
			return null;
		}
		
		return jsonObj.getAsJsonObject(name);
	}
	
	public static double optDouble(JsonObject jsonObj, String name, double defaultValue) {
		return Double.parseDouble(optString(jsonObj, name, defaultValue + ""));
	}
	
	public static int optInt(JsonObject jsonObj, String name, int defaultValue) {
		return Integer.parseInt(optString(jsonObj, name, defaultValue + ""));
	}

	public static String getString(JsonObject jsonObj, String name) {
		return optString(jsonObj, name, "");
	}
	
	public static String optString(JsonObject jsonObj, String name, String defaultValue) {
		if (null == jsonObj || null == jsonObj.get(name)) {
			return defaultValue;
		}

		return jsonObj.get(name).getAsString();
	}
}
